package com.tanhua.mongo.api;

import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveTimeLine(Movement movement) {
        //3 查询用户的好友信息
        //封装查询条件
        Query query = Query.query(Criteria.where("userId").is(movement.getUserId()));
        //执行查询
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

        try {
            TimeUnit.SECONDS.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //4 根据好友数据保存时间线数据
        for (Friend friend : friendList) {
            MovementTimeLine timeLine = new MovementTimeLine();
            timeLine.setMovementId(movement.getId()); //动态id
            timeLine.setUserId(movement.getUserId());//发布动态用户id
            timeLine.setFriendId(friend.getFriendId()); // 可见好友id
            timeLine.setCreated(movement.getCreated());//发布的时间

            mongoTemplate.save(timeLine);
        }
    }
}
